clear;
exec('circshift.sci');
stacksize('max');

N = 100;

//%%%%%%%%%%%%%%%%% формирование сигналов %%%%%%%%%%%%%%%%%

// Xadc = csvRead('D:\Program Files\ADC_data\Agl_1597_5_minus33.csv');
Xadc = csvRead('D:\Program Files\ADC_data\nois3_50dBm_GN22.csv');
//[x1, x2, x3, x4] = read_hex_data('D:\Program Files\ADC_data\nois3_60dBm_GN22\',1);
//Xadc = [x1; x2; x3; x4];

x = Xadc(:,1:$);//данные по строкам I-Q I-Q и т.д.
[num, len] = size(x);

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

//%%%%%%%%%%%%%%%%%%%% MATRIX %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

main = [1 2];
E = circshift(x(main,:)',2)';
//
//% Z = [x ; circshift(x',1)'; circshift(x',2)'; circshift(x',3)'; circshift(x',4)'; circshift(x',5)'];
//% Z(main,:) = [];
Z_data = x;
Z_data(main,:) = [];
n_delay = 4;
Z = [];

for i = 0:n_delay
    Z = [Z; circshift(Z_data',i)'];
end

//Z_ = Z_data(:,1:N);
//
//for i = 1:2:n_delay
//    Z_ = [Z_ ; Z( (i*(num-2)+1) : (i+1)*(num-2), 1:N)];
//    if i == n_delay then
//        break;
//    end
//    tmp = circshift(Z_data(:,1:N)',(i+1))';
//    Z_ = [Z_ ; tmp];
//end

db = [];
stdEout = [];
db_ = [];
stdEout_ = [];
wm = zeros(2,(num - 2)*(n_delay + 1));
wm_ = zeros(2,(num - 2)*(n_delay + 1));
step_iter = 500;
iter = 1;
//w_i = [];
//w_q = [];
//k = (2*(n_delay + 1))^(-1);
k = 0.9;
for i = 1:step_iter:len-N
    start = i;//grand(1,1,'uin',1,len-N);
    T = start:start+N-1;
//    T  = 1:len;
    E_ = E(:,i:N+i-1);
    Z_ = Z(:,i:N+i-1);
//    out = E_ - wm*Z_;
//
//    Rxx = Z_*Z_';
//    Rxd = out*Z_';
//    //pause
//    invRxx = inv(Rxx);
//    
//    wm = wm + Rxd*invRxx;
//    Eout = E(:,T) - wm*Z(:,T);
//    
//    stdEout = [stdEout, stdev(Eout, 'c')];
//    db = [db, 20*log10(stdev(E(:,T), 'c')./stdEout(:,iter))];

    Rxx = Z_*Z_';
    Rxd = E_*Z_';
    invRxx = inv(Rxx);
    wm_ = Rxd*invRxx;
//    w_i = [w_i;wm_(1,:)];
//    w_q = [w_q;wm_(2,:)];
    Eout_ = E(:,T) - wm_*Z(:,T);
    
    stdEout_ = [stdEout_, stdev(Eout_, 'c')];
    db_ = [db_, 20*log10(stdev(E(:,T), 'c')./stdEout_(:,iter))];
    
    iter = iter + 1;

end

//figure();
//plot(db');
figure();
plot(db_');

Rxx = Z*Z';
Rxd = E*Z';
w = Rxd/Rxx;
eout = E - w*Z;
disp(20*log10(stdev(E, 'c')./stdev(eout, 'c')));

//eout = E - [mean(w_i,'r'); mean(w_q,'r')]*Z;
//disp(20*log10(stdev(E, 'c')./stdev(eout, 'c')));
